using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.IO;

public class Synch : MonoBehaviour 
{
	public string Host;
	private int Port = 1057;
	private string readBuffer;
	
	public Model model;
	public UnitSpawner spawner;
	
    void Start ()
	{
        setupSocket();
		
		GameObject gameObj = GameObject.Find("HostOrClient");
		HostOrClient HoC = gameObj.GetComponent<HostOrClient>();
		MenuCommandMes MCm;
		if(HoC.Host)
		{
			MCm = new MenuCommandMes(Command.HOST_GAME, 0);
			MCm.pack();
			Send(MCm);
			model.playerNum = 0;
		}
		else
		{
			//MCm = new MenuCommandMes(Command.LIST_GAMES, 0);
			//MCm.pack();
			//Send(MCm);
			MCm = new MenuCommandMes(Command.JOIN_GAME, 0);
			MCm.pack();
			Send(MCm);
			model.playerNum = 1;
		}
		Destroy(gameObj);
    }
	
    void Update () 
	{
        readSocket();
    }
	
	public void Send(Message mes)
	{
		Writer.WriteLine(mes.messageBuffer);
		Writer.Flush();
	}
	
	private TcpClient Socket;
	private NetworkStream Stream;
	private StreamWriter Writer;
	private StreamReader Reader;
	private bool socketReady;
 
    public void setupSocket()
    {
        try
        {
            Socket = new TcpClient(Host, Port);
            Stream = Socket.GetStream();
            Writer = new StreamWriter(Stream);
            Reader = new StreamReader(Stream);
            socketReady = true;
        }
        catch (System.Exception e)
        {
            Debug.Log("Socket error: " + e);
            print("Connection failed");
        }
    }
 
    public void readSocket()
    {
        if (!socketReady)
            print ("Connection failed: Tried to read");
       
        if (Stream.DataAvailable)
		{
			while(Reader.Peek() != '\0')
			{
				int key = Reader.Read();
				ProcessData(key);
			}
		}
		ConfirmMes CMes = new ConfirmMes();
		CMes.pack();
		Send(CMes);
    }
	
	private void ProcessData(int key)
	{
		Reader.Read();
		readBuffer = Reader.ReadLine();
		switch(key)
		{
		case 'M':
		{
			MouseMes MouMes = new MouseMes(readBuffer);
			model.MouseMessage(MouMes);
		}
		break;
		//case 'M':
		case '9':
		{
			SystemMessage sysMes = new SystemMessage(readBuffer);
			model.SystemMessage(sysMes);
		}
		break;
		case 'S':
		{
			SpawnUnitMes spawnMes = new SpawnUnitMes(readBuffer);
			spawner.SpawnUnit(spawnMes);
		}
		break;
		case 'U':
		{
			new UpdateMes(readBuffer, spawner);
		}
		break;
		case 'D':
		{
			DeleteUnitMes delMes = new DeleteUnitMes(readBuffer);
			spawner.DeleteUnit(delMes.unitNum);
		}
		break;
		};
		//Reader.BaseStream.Flush();
		Reader.DiscardBufferedData();
		//Reader.BaseStream.Seek(0, SeekOrigin.Begin);
		Reader.BaseStream.Position = 0;
	}
}